package com.sam.im.heiqun.uis.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.sam.im.heiqun.R;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.EventBusType;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;

/**
 * Created by wangguodong on 2017/9/12.
 */

public class MyWebViewManageActivity extends BaseSwipeBackActivity {

    @BindView(R.id.webview_my)
    WebView webview;
    @BindView(R.id.webview_progress)
    ProgressBar webview_progress;

    private WebSettings webSettings;

    private int showType = 0 ;//0-
    private String showUrl = "" ;//
    private String uid = "" ;//
    private int isGroup = 1 ;//

    public static void start(Context activity, int showType, String showUrl) {
        Intent intent = new Intent(activity, MyWebViewManageActivity.class);
        intent.putExtra("showType", showType);
        intent.putExtra("showUrl", showUrl);
        activity.startActivity(intent);
    }
    public static void start(Context activity, int showType, String showUrl, String uid, int isGroup) {
        Intent intent = new Intent(activity, MyWebViewManageActivity.class);
        intent.putExtra("showType", showType);
        intent.putExtra("showUrl", showUrl);
        intent.putExtra("uid", uid);
        intent.putExtra("isGroup", isGroup);
        activity.startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onBaseEvent(final Integer refresh) {
        if (refresh == EventBusType.RESULT_REPORT_SUCCESS){
            finish();
        }
    }

    @Override
    protected String getTitleText() {
        showType = getIntent().getIntExtra("showType",0);
        showUrl = getIntent().getStringExtra("showUrl");
        isGroup = getIntent().getIntExtra("isGroup",1);
        uid = getIntent().getStringExtra("uid");
        String title = "";
        switch (showType){
            case 0 :
                title = getResources().getString(R.string.look_look) ;
                break;
            case 1 :
                title = getResources().getString(R.string.help_feedback) ;
                break;
            case 2 :
                title = getResources().getString(R.string.small_project) ;
                break;
            case 3 :
                title = getResources().getString(R.string.complaint) ;
                break;
            case 4 :
                title = getResources().getString(R.string.black_group_privacy_protection) ;
                break;
        }
        return title;
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {

        //设置webview 设置缩放等级,100代表不做任何缩放
        webview.setInitialScale(100);
        //设置webview可触摸放大缩小
        webview.getSettings().setSupportZoom(true);
        //设置显示缩放按钮
        webview.getSettings().setBuiltInZoomControls(true);
        //将图片调整到适合webview的大小
        webview.getSettings().setUseWideViewPort(true);

//        webview.setLayerType();
//        webview.setDrawingCacheEnabled(true);

        //获取WebSettings对象
        webSettings = webview.getSettings();
        //设置webview支持运行普通的Javascript
        webSettings.setJavaScriptEnabled(true);
        // 设置允许JS弹窗
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //阻止网络图片加载
        webSettings.setBlockNetworkImage(false);

        //不显示webview缩放按钮
        webSettings.setDisplayZoomControls(false);

        webSettings.setDefaultTextEncodingName("GBK");//设置字符编码


//        webSettings.setUserAgentString(webSettings.getUserAgentString() + APP_NAME_UA);

        /*webview有两个方法：setWebChromeClient和setWebClient
            setWebChromeClient主要处理解析，渲染网页等浏览器做的事情
            WebChromeClient是辅助WebView处理Javascript的对话框，网站图标，网站title，加载进度等

            简单的说，如果除了加载HTML的话，只需要用WebViewClient即可，
            但是在进行兼容互联网上附加javascript的页面的时候和调用javascript对话框的时候，
            或者功能较为复杂的内嵌操作的时候，建议使用WebChromeClient 。
            */

        //点击超链接后不弹出浏览器窗口，而在webview控件中加载URL
        webview.setWebViewClient(new WebViewClient() {
//            @Override
//            public void onPageStarted(WebView view, String url, Bitmap favicon) {
////                if (url.contains("samim:report")){
//////                    showToast("监听到了samim:report！！！！！！！！！！！");
////
////                }else {
////
////                }
//                super.onPageStarted(view, url, favicon);
//            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //允许加载网络图片
                webview.getSettings().setBlockNetworkImage(false);
                webview.getSettings().setDomStorageEnabled(true);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if(url.contains("samim:report")){
                    ComplaintEvidenceActivity.start(MyWebViewManageActivity.this,uid,isGroup);
                    return true;
                }else if (url.contains("samim:/chat/feedback_form")){
                    String id = url.substring(url.indexOf("feedback_form?id=")+17);
                    Log.i("wgdinfo", "shouldOverrideUrlLoading: ==============id="+id);
                    FeedBackActivity.start(MyWebViewManageActivity.this, id);
                    return true;
                }
                else {
                    //这里不需要跳转，onPageStarted中已经加载过了
//                    view.loadUrl(url);
//                    return true;
                    return false;
                }
            }
        });
        // 设置setWebChromeClient对象
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                Log.d("ANDROID_LAB", "TITLE=" + title);
//                txtTitle.setText("ReceivedTitle:" +title);
//                if (4 == showType || 5 == showType || 6 == showType) setTitle(title);
            }

            @Override
            public void onProgressChanged(WebView webView, int i) {
//                super.onProgressChanged(webView, i);
                if (i <= 100) {
                    if (null != webview_progress) {
                        webview_progress.setProgress(i);
                        webview_progress.setVisibility(View.VISIBLE);
                    }
//                    if (mProgressDialog != null ){
//                        mProgressDialog.setMessage(i + "%");
//                        if (!isFinishing() && !mProgressDialog.isShowing())mProgressDialog.show();
//                    }
                } else {
                    if (null != webview_progress) webview_progress.setVisibility(View.GONE);
//                    if (!isFinishing() && mProgressDialog != null && mProgressDialog.isShowing())mProgressDialog.dismiss();// 请求成功,关闭ProgressDialog
                }
            }
        });
        Log.i("-----", "initView:  WebView 加载的url == " + showUrl);
        webview.loadUrl(showUrl);

    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_my_webview ;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
            webview.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
